# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=whisper.cpp
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
epoch=1
_pkgver=1.7.5
pkgver=1.7.5.r245.g13d92d08
pkgrel=1
pkgdesc="Port of OpenAI's Whisper model in C/C++ (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64' 'mingw64')
url='https://github.com/ggml-org/whisper.cpp'
license=('spdx:MIT')
depends=(
  "${MINGW_PACKAGE_PREFIX}-cc-libs"
  "${MINGW_PACKAGE_PREFIX}-ggml"
  "${MINGW_PACKAGE_PREFIX}-SDL2"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "git"
)
_commit=13d92d08ae26031545921243256aaaf0ee057943
source=("git+https://github.com/ggml-org/whisper.cpp#commit=${_commit}"
        "0001-missing-include.patch")
sha256sums=('6b024e36c17e9bccd904887a8e6b81ca57970ad38ba35997a3ec9fdef92d669b'
            '8b861c09c309e6196f5316ddb9d768570eba8de12784e3a021e02c59968ef47a')

pkgver() {
  cd "${_realname}"
  git describe --long --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
}

prepare() {
  cd "${_realname}"

  patch -p1 < ../0001-missing-include.patch
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${CARCH} == aarch64 ]]; then
    extra_config+=("-DWHISPER_NO_AVX=ON" "-DWHISPER_NO_AVX2=ON" "-DWHISPER_NO_FMA=ON" "-DWHISPER_NO_F16C=ON")
  fi

  LDFLAGS+=" -Wl,--export-all-symbols" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DWHISPER_USE_SYSTEM_GGML=ON \
      -DWHISPER_CURL=ON \
      -DWHISPER_SDL2=ON \
      -DWHISPER_BUILD_EXAMPLES=ON \
      -DBUILD_SHARED_LIBS=ON \
      -DWHISPER_ALL_WARNINGS=OFF \
      "${extra_config[@]}" \
      ../${_realname}

  cmake --build .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" cmake --install .

  # Rename output files by prefixing them with whisper (if not already prefixed and if not DLL)
  for i in "${pkgdir}"${MINGW_PREFIX}/bin/*.{exe,py,sh}; do
    filename=$(basename "$i")
    
    if [[ -e $i && ! ("$filename" =~ ^whisper) ]]; then
      mv "${i}" "${pkgdir}${MINGW_PREFIX}/bin/whisper-${filename}"
    fi
  done

  install -Dm755 "${srcdir}/${_realname}/models/download-ggml-model.sh" \
    "${pkgdir}${MINGW_PREFIX}/bin/whisper-download-ggml-model.sh"

  install -Dm644 "${srcdir}"/${_realname}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
